package com.cz.nongyetongv5.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.application.InitApplication;
import com.cz.nongyetongv5.bean.JsonUtil;
import com.cz.nongyetongv5.bean.PatrolDetailBean;
import com.cz.nongyetongv5.bean.PatrolList;
import com.cz.nongyetongv5.bean.PatrolListBean;
import com.cz.nongyetongv5.bean.PatrolListResponse;
import com.cz.nongyetongv5.bean.User;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

public class AssistPatrolListActivity extends Activity implements View.OnClickListener {
    private RelativeLayout btnBack;
    RecyclerView recyclerView;
    SmartRefreshLayout refreshLayout;
    private int page = 1;
    private int size = 10;


    private String region_code;
    private String region_name;
    private String year;
    private User user;
    private String type;
    private int status = 0;


    private PatrolListResponse patrolListResponse;
    private PatrolListBean patrolListBean;
    private List<PatrolList> patrolLists;

    private PatrolListAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_assist_patrol_list);
        btnBack = findViewById(R.id.btnBack);
        btnBack.setOnClickListener(this);
        recyclerView = findViewById(R.id.recyclerView);
        refreshLayout = findViewById(R.id.refreshLayout);
        user = (User) getIntent().getSerializableExtra("user");
        region_code = getIntent().getStringExtra("region_code");
        region_name = getIntent().getStringExtra("name");
        year = getIntent().getStringExtra("year");
        type = getIntent().getStringExtra("type");
        status = getIntent().getIntExtra("status", 0);

        patrolLists = new ArrayList<>();
        adapter = new PatrolListAdapter();
        View notDataView = getLayoutInflater().inflate(R.layout.view_nodata, (ViewGroup) recyclerView.getParent(), false);
        adapter.setEmptyView(notDataView);
        recyclerView.setLayoutManager(new LinearLayoutManager(AssistPatrolListActivity.this));
        recyclerView.setAdapter(adapter); //设置分页和下拉刷新
        refreshLayout.setDisableContentWhenRefresh(true);
        refreshLayout.setDisableContentWhenLoading(true);
        refreshLayout.setRefreshHeader(new ClassicsHeader(AssistPatrolListActivity.this));
        //设置 Footer
        refreshLayout.setRefreshFooter(new ClassicsFooter(AssistPatrolListActivity.this));
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                getPatrolList();
                //                WaitDialog.ShowDialog(getActivity(),"数据加载中...");

            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                if (patrolListBean != null) {
                    if (page < patrolListBean.getTotal()) {
                        page++;
                        getPatrolList();
                    } else {
                        refreshLayout.finishLoadmore();
                        Toast.makeText(AssistPatrolListActivity.this, "没有更多数据", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    refreshLayout.finishLoadmore();
                    Toast.makeText(AssistPatrolListActivity.this, "没有数据", Toast.LENGTH_SHORT).show();
                }


            }
        });
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                getPatrolDetail(patrolLists.get(position).getCheck_id(), patrolLists.get(position).getAdd_user());
            }
        });

        getPatrolList();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnBack:
                finish();
                break;
            default:
                break;
        }
    }

    public int getSize() {
        return patrolLists.size();
    }

    public void setSelect(boolean isSelect) {
        for (PatrolList patrolList : patrolLists) {
            patrolList.setChecked(isSelect);
        }
        adapter.notifyDataSetChanged();
    }


    /**
     * 获取选中的item
     *
     * @return
     */
    public List<PatrolList> getSelected() {
        List<PatrolList> selectedItems = new ArrayList<>();
        for (PatrolList patrolList : patrolLists) {
            if (patrolList.isChecked()) {
                selectedItems.add(patrolList);
            }
        }
        return selectedItems;
    }


    void getPatrolDetail(String id, final String add_user) {
        OkHttpUtils
                .get()
                .url(InitApplication.newUrl + "check/checkCheckDetail.json")
                .addParams("addFrom", "1")
                .addParams("addMark", "android")
                .addParams("check_id", id)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(AssistPatrolListActivity.this, "请求失败，稍后再试", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        //                        System.out.println(response);
                        Gson gson = new Gson();
                        PatrolDetailBean patrolDetailBean = gson.fromJson(response, PatrolDetailBean.class);
                        if (patrolDetailBean.getCode() == 0) {
                            if (patrolDetailBean.getData() != null) {
                                Intent intent = new Intent(AssistPatrolListActivity.this, PatrolDetailActivity.class);
                                intent.putExtra("add_user", add_user);
                                intent.putExtra("region_code", region_code);
                                intent.putExtra("type", 1);
                                intent.putExtra("patrolBean", patrolDetailBean.getData());
                                startActivity(intent);
                            } else {
                                Toast.makeText(AssistPatrolListActivity.this, "请求失败，稍后再试", Toast.LENGTH_SHORT).show();
                            }

                        } else {
                            Toast.makeText(AssistPatrolListActivity.this, "请求失败，稍后再试", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }


    void getPatrolList() {
        if (status == 1) {
            OkHttpUtils
                    .get()
                    .url(InitApplication.newUrl + "check/checkMonthOrYearList.json")
                    .addParams("addFrom", "1")
                    .addParams("addMark", "android")
                    .addParams("page", String.valueOf(page))
                    .addParams("size", String.valueOf(size))
//                    .addParams("region_code", region_code)
                    .addParams("username", region_name)
                    .addParams("type", type)
                    .addParams("year", year)
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            closeRefresh();
                            Toast.makeText(AssistPatrolListActivity.this, "请求失败，稍后再试", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onResponse(String response, int id) {
                            System.out.println(response);
                            closeRefresh();
                            patrolListResponse = JsonUtil.toObject(response, PatrolListResponse.class);
                            if (patrolListResponse.getCode() == 0) {
                                patrolListBean = patrolListResponse.getData();
                                if (page == 1) {
                                    patrolLists.clear();
                                    patrolLists.addAll(patrolListBean.getRows());
                                } else {
                                    patrolLists.addAll(patrolListBean.getRows());
                                }
                                adapter.notifyDataSetChanged();
                            } else {
                                Toast.makeText(AssistPatrolListActivity.this, "请求失败，稍后再试", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
        } else {
            OkHttpUtils
                    .get()
                    .url(InitApplication.newUrl + "check/checkMonthOrYearList.json")
                    .addParams("addFrom", "1")
                    .addParams("addMark", "android")
                    .addParams("page", String.valueOf(page))
                    .addParams("size", String.valueOf(size))
                    .addParams("region_code", region_code)
//                .addParams("username", region_name)
                    .addParams("type", type)
                    .addParams("year", year)
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            closeRefresh();
                            Toast.makeText(AssistPatrolListActivity.this, "请求失败，稍后再试", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onResponse(String response, int id) {
                            System.out.println(response);
                            closeRefresh();
                            patrolListResponse = JsonUtil.toObject(response, PatrolListResponse.class);
                            if (patrolListResponse.getCode() == 0) {
                                patrolListBean = patrolListResponse.getData();
                                if (page == 1) {
                                    patrolLists.clear();
                                    patrolLists.addAll(patrolListBean.getRows());
                                } else {
                                    patrolLists.addAll(patrolListBean.getRows());
                                }
                                adapter.notifyDataSetChanged();
                            } else {
                                Toast.makeText(AssistPatrolListActivity.this, "请求失败，稍后再试", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
        }
    }


    public class PatrolListAdapter extends BaseQuickAdapter<PatrolList, BaseViewHolder> {
        public PatrolListAdapter() {
            super(R.layout.patrol_list_item, patrolLists);
        }

        @Override
        protected void convert(BaseViewHolder helper, PatrolList item) {


            if (item.getType() != null && item.getType().equals("1")) {
                helper.setText(R.id.tv_patrol_addr, "巡查对象:");
                helper.setText(R.id.tv_record_hit, "巡查内容:");
                if (item.getCheck_address() != null) {
                    helper.setText(R.id.tv_product_name, item.getEnt_name());
                } else {
                    helper.setText(R.id.tv_product_name, "--");
                }

                if (item.getContent() != null) {
                    helper.setText(R.id.tv_record, item.getContent());
                } else {
                    helper.setText(R.id.tv_record, "--");
                }
            } else {
                helper.setText(R.id.tv_patrol_addr, "巡查地点:");
                helper.setText(R.id.tv_record_hit, "巡查记录:");
                if (item.getCheck_address() != null) {
                    helper.setText(R.id.tv_product_name, item.getCheck_address());
                } else {
                    helper.setText(R.id.tv_product_name, "--");
                }

                if (item.getCheck_record() != null) {
                    helper.setText(R.id.tv_record, item.getCheck_record());
                } else {
                    helper.setText(R.id.tv_record, "--");
                }


            }

            if (item.getRealname() != null) {
                helper.setText(R.id.tv_admin, item.getRealname() + "(" + item.getRegion_name() + ")");
            }
            if (item.getCheck_time() != null) {
                helper.setText(R.id.tv_date, item.getCheck_time());
            }


            helper.setVisible(R.id.cb_choose, false);

            Glide.with(AssistPatrolListActivity.this)
                    .load(item.getAttach_url()).placeholder(R.drawable.loading).error(R.mipmap.ic_launcher)
                    .into((ImageView) helper.getView(R.id.iv_iv));

        }
    }

    public void closeRefresh() {
        if (refreshLayout != null) {
            if (refreshLayout.isRefreshing()) {
                refreshLayout.finishRefresh();
            } else if (refreshLayout.isLoading()) {
                refreshLayout.finishLoadmore();
            }
        }
    }


}
